package com.shangye.core;

import com.shangye.http.HttpServletRequest;
import com.shangye.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {

    private static File rootDir;
    private static File staticDir;

    static {
        try {
            rootDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(rootDir, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private static DispatcherServlet instance = new DispatcherServlet();

    private DispatcherServlet() {
    }

    public static DispatcherServlet getInstance() {
        return instance;
    }

    // 处理请求
    public void service(HttpServletRequest request, HttpServletResponse response) {

        String path = request.getUri();
        System.out.println(path);
        File file = new File(staticDir, path);
        System.out.println("文件是否存在：" + file.exists());
        if (file.exists()) {
            response.addHeaders("Content-Type: ","text/html");
            response.addHeaders("Content-Length: ",file.length()+"");
            response.setContentFile(file);
        } else {
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File(staticDir, "root/404.html");
            response.setContentFile(file);
            response.addHeaders("Content-Type: ","text/html");
            response.addHeaders("Content-Length: ",file.length()+"");
        }
    }
}
